import { Component, TemplateRef, ViewChild } from '@angular/core';
import { Subject } from 'rxjs';
import { MessageboxService } from '@iux/live';

@Component({
  templateUrl: './customize.component.html',
})
export class CustomizeComponent {
  warningConfirm: boolean = false;
  valid$ = new Subject<boolean>();
  @ViewChild('contentTpl', { static: false }) contentTpl: TemplateRef<any>;
  @ViewChild('warningContentTpl', { static: true }) warningContentTpl: TemplateRef<any>;

  constructor(private messageBox: MessageboxService) {}

  confirm(): void {
    this.messageBox.confirm({
      lvHeader: 'Unconfirm this alert?',
      lvDialogIcon: '',
      lvOk: () =>
        new Promise<void>((resolve) => {
          setTimeout(() => {
            resolve();
          }, 2000);
        }),
      lvOkLoadingText: 'Asynchronous loading',
      lvModalKey: 'myModal',
    });
  }

  info(): void {
    this.messageBox.info({
      lvHeader: 'Custom title',
      lvContent: 'This is a content dialog.',
      lvModalKey: 'myModal',
    });
  }

  success(): void {
    this.messageBox.success({
      lvContent: this.contentTpl,
      lvModalKey: 'myModal',
    });
  }

  error(): void {
    this.messageBox.error({
      lvContent: 'This is a custom width dialog.',
      lvWidth: '50%',
      lvModalKey: 'myModal',
      lvAfterOpen: (modal) => {
        let timer = 5;
        modal.lvOkText = `OK (${timer}s)`;

        const interval = setInterval(() => {
          timer--;
          modal.lvOkText = `OK (${timer}s)`;
        }, 1000);

        const timeOut = setTimeout(() => {
          clearInterval(interval);
          clearTimeout(timeOut);
          modal.close();
        }, 5000);

        modal.openState$.subscribe((state) => {
          if (!state) {
            clearInterval(interval);
            clearTimeout(timeOut);
          }
        });
      },
    });
  }

  warning(): void {
    this.messageBox.warning({
      lvContent: 'This is a warning dialog.',
      lvModalKey: 'myModal',
      lvOk: () => {
        this.messageBox.danger('This is a danger dialog.');
      },
    });
  }

  custom(): void {
    this.messageBox.confirm({
      lvDialogIcon: 'lv-icon-status-danger',
      lvContent: this.warningContentTpl,
      lvOkType: 'primary',
      lvCancelType: 'default',
      lvOkDisabled: !this.warningConfirm,
      lvModalKey: 'myModal',
      lvBeforeOpen: () => {
        this.warningConfirm = false;
      },
      lvAfterOpen: (modal) => {
        this.valid$.subscribe((e) => {
          modal.lvOkDisabled = !e;
        });
      },
      lvOk: () =>
        new Promise<void>((resolve) => {
          setTimeout(() => {
            resolve();
          }, 2000);
        }),
    });
  }

  modalCheckBoxChange(e): void {
    this.valid$.next(e);
  }
}
